package com.aopcinemas.visitor.behaviour;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import com.aopcinemas.visitor.VisitorAgent;
import com.aopcinemas.visitor.VisitorConstants;
import com.aopcinemas.visitor.ontology.GetCampaign;
import com.aopcinemas.visitor.ontology.VisitorOntology;

public class CampaignSearchBehavior extends TickerBehaviour {

	private static final long serialVersionUID = 1L;
	
	private long period = 10000;

    public CampaignSearchBehavior(Agent agent) {
        super(agent, 10000);
    }

    @Override
    protected void onTick() {

        System.out.println("CampaignSearchBehavior");
        VisitorAgent agent = (VisitorAgent) myAgent;

        if (agent.getGetCampaign() != null) {
            GetCampaign getCampaign = agent.getGetCampaign();
            if (period != getCampaign.getPeriod()) {
                reset(getCampaign.getPeriod());
            }

            DFAgentDescription template = new DFAgentDescription();
            ServiceDescription sd = new ServiceDescription();
            sd.setType(VisitorConstants.VISITOR_COMPAIGN);
            template.addServices(sd);

            try {
                DFAgentDescription[] result = DFService.search(myAgent, template);
                System.out.println("found campaign cervices: " + result.length);
                for (int i = 0; i < result.length; ++i) {
                    ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
                    message.setLanguage(agent.getCodec().getName());
                    message.setOntology(VisitorOntology.getInstance().getName());
                    message.addReceiver(result[i].getName());
                    
                    try {
                        agent.getContentManager().fillContent(message, new Action(result[i].getName(), getCampaign));
                    } catch (CodecException e) {
                        e.printStackTrace();
                    } catch (OntologyException e) {
                        e.printStackTrace();
                    }
                    agent.addBehaviour(new CampaignInfoInitiator(agent, message));
                }
            } catch (FIPAException e) {
                throw new RuntimeException("Can't find campaigns");
            }

        }

    }
}
